const axios = require('axios');
const { dialog } = require('electron');
const { db, getServerAddress } = require('./db');
const { closeLoginWindow, createMainWindow } = require('./windowManager');

async function handleUserLogin(event, username, password) {
    try {
        let serverAddress = getServerAddress();
        if (!serverAddress) throw new Error("服务器地址没有配置");
        if (!username || !password) throw new Error("用户名或密码不能为空");

        const loginUrl = `http://${serverAddress}/api/login/`;
        console.log(`Logging in with ${username} at ${loginUrl}`);

        const postData = {
            username: username,
            password: password
        };

        const response = await axios.post(loginUrl, postData);
        console.log(response.data); // 处理成功情况

        // 登录成功后关闭登录窗口并打开主窗口
        event.sender.send('login-success'); // 发送登录成功的消息给渲染进程
        closeLoginWindow(); // 关闭登录窗口
        createMainWindow(); // 打开主应用窗口

        return response.data;
    } catch (error) {
        let message;
        if (error.response && error.response.status >= 400) {
            message = "服务器连接失败，请检查服务器地址及网络连接";
        } else if (error.request) {
            message = "未能从服务器接收到响应，请检查服务器地址及网络连接";
        } else {
            message = error.message;
        }

        dialog.showErrorBox('登录失败', message);
        throw new Error(message);
    }
}

module.exports = { handleUserLogin };